# coding=utf-8
'''
Created on 2016年9月27日

@author: hhl
'''

import urllib2
import sys
from gevent import Greenlet
import gevent
import datetime
import time

sys = sys
if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')
    
from wxvideo.catchserve.letv import letv_catch

TIME_DELTA = 10800


class DelayCall:
    """延迟调用对象\n
    """
    
    def __init__(self,f,*args,**kw):
        """
        @param f: function f是一个function对象\n
        @param args: f的必要参数\n
        @param kw: f的可选参数\n
        """
        self.f = f
        self.args = args
        self.kw = kw
    
    def call(self):
        """调用执行函数，并且返回结果\n
        """
        return self.f(*self.args,**self.kw)

class Timer(Greenlet):
    
    def __init__(self,seconds,f,*args,**kw):
        """以一个微线程的方式实现一个定时器\n
        """
        Greenlet.__init__(self)
        self.seconds = seconds
        self.delay_call = DelayCall(f,*args,**kw)
        
    def cancel(self):
        """取消定时器\n
        """
        self.kill()
        
    def _run(self):
        """通过sleep进行延迟调用注册的函数,这里的sleep与线程的sleep不同，他是基于微线程的\n
        """
        gevent.sleep(self.seconds)
        return self.delay_call.call()
    
def callLater(seconds,f, *args, **kw):
    assert callable(f), "%s is not callable" % f
    assert seconds >= 0,"%s is not greater than or equal to 0 seconds" % (seconds,)
    t = Timer(seconds, f,*args, **kw)
    t.start()
    return t

def catch_info():
    letv_catch.get_movie(30)
    letv_catch.get_movie_nofree(30)
    letv_catch.get_hot_movie(30)
    

def schedule_date():
    today = datetime.date.today()
    ss = datetime.datetime(today.year,today.month,today.day,11,0,0)-datetime.datetime.now()
    delta = ss.seconds
    callLater(delta, catch_info)
    callLater(delta, schedule_date)

def start():
    while True:
        gevent.sleep(600)
    
if __name__ == '__main__':
#     print 'start'
#     from gtwisted.core import reactor
#     def handler():
        gevent.joinall([gevent.spawn(schedule_date),
                    gevent.spawn(start),
                    ])
#         reactor.callLater(TIME_DELTA, handler)
#     reactor.callLater(2, handler)
#     reactor.run()
#     print 'ok'